#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

int64_t line = 0;      
int64_t words = 0;     
int64_t character = 0;

bool isAlphabet(char c)
{
    return ((c >= 'a' && c <= 'z') || ( c >= 'A' && c <= 'Z'));
}

void count(char* buffer)
{
    char* p = buffer;
    while(1)
    {

        while(!isAlphabet(*p))
        {
            if(*p == '\0')
                return;
            character++;
            if(*p == '\n')
                line++;
            p++;
        }//此时*p是字符

        words++;
        while(isAlphabet(*p))
        {
            p++;
            character++;
        }
    }
}

int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "The way of use is: ./wc file\n");
        exit(1);
    }

    FILE* stream = fopen(argv[1], "rb");
    if(stream == NULL)
    {
        fprintf(stderr, "open %s failed\n", argv[1]);
        exit(1);
    }

    fseek(stream, 0, SEEK_END);
    size_t size = (size_t)ftell(stream);
    rewind(stream);

    char* buffer = (char*)calloc(size + 1, sizeof(char));
    if(buffer == NULL)
    {
        fprintf(stderr, "Error: calloc failed\n");
        exit(1);
    }

    size_t num = fread(buffer, 1, size, stream);
    if(num < size)
    {
        fprintf(stderr, "Erroe: read failed\n");
        exit(1);
    }
    buffer[size] = '\0';

    count(buffer);

    printf("line = %ld, words = %ld, character = %ld\n", line, words, character);

    return 0;
}

